package struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import annotation.ActionConfigBean;
import struts.form.ActionForm;
import struts.form.FullForm;
import struts.form.XmlBean;

public class ActionServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 7320431028733786256L;
    
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        //获取请求头
        String path = getPath(request.getServletPath());
        @SuppressWarnings("unchecked")
        Map<String,ActionConfigBean> map = (Map<String, ActionConfigBean>) this.getServletContext().getAttribute("struts");
        String formclass = map.get(path).getForm().getName();
        ActionForm form = FullForm.full(formclass, request);
        String actionclass = map.get(path).getAction().getName();
        Action action = null;
        String url = "";
        try{
            Class<?> clazz = Class.forName(actionclass);
            action = (Action)clazz.newInstance();
            url = action.execute(request, form,map.get(path));
        }catch(Exception e) {
            e.printStackTrace();
            System.out.println("严重：控制器异常！");
        }
        
        RequestDispatcher dis = request.getRequestDispatcher(url);
        dis.forward(request, response);
        
    }
    
    
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        this.doGet(request, response);
    }
    
    private String getPath(String servletPath) {
        return servletPath.split("\\.")[0];
    }
}
